package com.cheejee.oss.config;

import java.io.File;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.cheejee.oss.service.StorageService;
import com.cheejee.service.oss.impl.AliStorateServiceImpl;
import com.cheejee.service.oss.impl.LocalStorageServiceImpl;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author CARRY
 * @Date 2020年11月6日上午12:35:54
 */
@Data
@EqualsAndHashCode(callSuper=true)
@Configuration
public class OssConfig extends WebMvcConfigurationSupport {

	@Value("${oss-type}")
	private String ossType;

	// 阿里OSS配置
	@Value("${ali.endpoint}")
	private String endpoint;

	@Value("${ali.access-keyId}")
	private String accessKeyId;

	@Value("${ali.access-key-secret}")
	private String accessKeySecret;

	@Value("${ali.bucket-name}")
	private String bucketName;

	// 本地OSS配置
	@Value("${local.relative-path}")
	private String relativePath;
	
	@Value("${local.absolute-path}")
	private String absolutePath;

	@Bean
	public StorageService storateServcie() {
		switch (ossType) {
		case "1":
			new File(absolutePath).mkdirs();
			return new LocalStorageServiceImpl(absolutePath, relativePath);

		case "2":
			return new AliStorateServiceImpl(endpoint, accessKeyId, accessKeySecret, bucketName);

		default:
			return null;
		}
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler(relativePath + "**").addResourceLocations("file:/" + absolutePath);
		super.addResourceHandlers(registry);
	}

}
